<template>
  <div>
    <SearchForm
        @search="onSearch"
        @reset="onReset"
        :search-list="searchList"
        :search-params="searchParams">
    </SearchForm>

    <div class="table-layout">
      <el-card shadow="never">
        <div class="table-handle">
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="onAdd">新增采购单</el-button>
        </div>
        <div class="table-box">
          <el-table
              size="large"
              stripe
              border
              v-loading="loading"
              max-height="500px"
              :data="tableData"
              row-key="id"
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(255, 255, 255, 0.8)"
              @selection-change="onSelect"
          >
            <el-table-column prop="id" label="ID" width="60"/>
            <el-table-column prop="menu_date" label="菜单日期" width="120">
              <template slot-scope="scope">
                {{ formatDate(scope.row.menu_date) }}
              </template>
            </el-table-column>
            <el-table-column prop="title" label="菜单标题" min-width="150"/>
            <el-table-column prop="description" label="菜单描述" min-width="200" show-overflow-tooltip/>
<!--            <el-table-column prop="monthly_bidding_title" label="比价项目" min-width="150" show-overflow-tooltip/>-->
            <el-table-column prop="supplier.name" label="供应商" width="120"/>
            <el-table-column prop="purchaser.name" label="采购员" width="100"/>
            <el-table-column prop="status" label="状态" width="100">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.status === 0" type="warning">草稿</el-tag>
                <el-tag v-if="scope.row.status === 1" type="warning">待采购</el-tag>
                <el-tag v-if="scope.row.status === 2" type="primary">已采购</el-tag>
                <el-tag v-if="scope.row.status === 3" type="success">已收货</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="create_time" label="创建时间" width="160">
              <template slot-scope="scope">
                {{ formatDateTime(scope.row.create_time) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="280">
              <template slot-scope="scope">
                <el-button type="text" v-if="scope.row.status === 0" @click="onEdit(scope.row)">编辑</el-button>
                <el-button type="text"  v-if="scope.row.status === 0 || scope.row.status === 1" @click="onSelectDishes(scope.row)">选择菜品</el-button>
                <el-button type="text" v-if="scope.row.status === 0" @click="onPublish(scope.row)">提交</el-button>
                <el-button type="text" v-if="scope.row.status === 2" @click="onConfirmReceipt(scope.row)">确认收货</el-button>
                <el-button type="text" v-if="scope.row.status === 3" @click="onViewReceiptDetails(scope.row)">查看明细</el-button>

                <el-button type="text" style="color: #F82222" @click="onDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
      <div class="page-box">
        <el-pagination
            background
            :current-page="pageNo"
            :page-sizes="pageSizes"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalSize"
            @size-change="changePageSize"
            @current-change="changePageNo"
        />
      </div>
    </div>
    <Add ref="addFormRef" @get-page="initData" />
    <DishSelector
      :visible.sync="showDishSelector"
      :monthly-bidding-id="currentMenu?.monthly_bidding_id"
      :supplier-id="currentMenu?.supplier_id"
      :current-menu="currentMenu"
      @success="onDishSelectionSuccess"
    />
    <ConfirmReceipt
      :visible.sync="showConfirmReceipt"
      :current-menu="currentMenu"
      @success="onConfirmReceiptSuccess"
    />
    <ReceiptDetails
      :visible.sync="showReceiptDetails"
      :current-menu="currentMenu"
    />
  </div>
</template>

<script>
import crud from "@/mixins/crud";
import { http } from "@/api";
import Add from "./add";
import DishSelector from "./dishSelector";
import ConfirmReceipt from "./confirmReceipt";
import ReceiptDetails from "./receiptDetails";

export default {
  name: "DailyMenuIndex",
  components: {
    Add,
    DishSelector,
    ConfirmReceipt,
    ReceiptDetails
  },
  mixins: [crud],
  data() {
    return {
      request: http.dailyMenu,
      searchList: [
        {
          label: '菜单标题',
          prop: 'title',
          name: 'input',
          placeholder: '请输入菜单标题'
        },
        {
          label: '菜单日期',
          prop: 'menu_date',
          name: 'datetime',
          type: 'date',
          valueFormat: 'yyyy-MM-dd',
          placeholder: '请选择菜单日期'
        },
        // {
        //   label: '供应商',
        //   prop: 'supplier_id',
        //   name: 'input',
        //   placeholder: '请输入供应商名称'
        // },
        // {
        //   label: '采购员',
        //   prop: 'purchaser_id',
        //   name: 'input',
        //   placeholder: '请输入采购员姓名'
        // },
        {
          label: '状态',
          prop: 'status',
          name: 'select',
          options: [
            { value: 0, label: '草稿' },
            { value: 1, label: '待采购' },
            { value: 2, label: '采购中' },
            { value: 3, label: '已收货' },
            { value: 4, label: '已完成' }
          ]
        }
      ],
      searchParams: {
        title: '',
        menu_date: '',
        supplier_name: '',
        purchaser_name: '',
        status: ''
      },
      defaultParams: {
      },
      tableData: [],
      // 菜品选择相关
      showDishSelector: false,
      currentMenu: null,
      // 确认收货相关
      showConfirmReceipt: false,
      // 查看收货明细相关
      showReceiptDetails: false
    }
  },
  methods: {
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return date.toLocaleDateString('zh-CN');
    },

    formatDateTime(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },

    onViewDetails(row) {
      // 查看采购单明细
      this.$message.info('查看明细功能待实现');
    },

    onSelectDishes(row) {
      // 选择菜品明细
      this.currentMenu = row;
      this.showDishSelector = true;
    },

    onDishSelectionSuccess() {
      // 菜品选择成功后的回调
      // this.$message.success('菜品明细已添加到采购单');
      // 可以在这里刷新列表或进行其他操作
    },
    onPublish(row) {
      // 确认对话框
      this.$confirm('确定发布该采购单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.loading = true
        try {
          // 先查询菜品明细
          const list = await http.dailyMenuItem.list({
            daily_menu_id: row.id
          });
          if (list.data.length === 0) {
            this.$message.error('请先选择菜品明细');
            return false;
          }
          await http.dailyMenu.update(row.id, {
            status: 1
          });
          this.onSearch();
          this.$message.success('发布成功');
        } catch (error) {
          console.error(error);
        } finally {
          this.loading = false
        }
      });
    },
    onConfirmReceipt(row) {
      // 打开确认收货弹窗
      this.currentMenu = row;
      this.showConfirmReceipt = true;
    },
    
    onConfirmReceiptSuccess() {
      // 确认收货成功后的回调
      this.onSearch(); // 刷新列表
    },
    
    onViewReceiptDetails(row) {
      // 查看收货明细
      this.currentMenu = row;
      this.showReceiptDetails = true;
    }
  }
}
</script>

<style scoped lang="scss">
.table-layout {
  margin-top: 20px;
}
.table-handle {
  margin-bottom: 20px;
}
.page-box {
  margin-top: 20px;
  text-align: right;
}
</style>
